package com.sam.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;


import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class JpaConfig {

    @Bean(name = "routingDataSource")
    public DynamicDataSourceRouter routingDataSource(@Qualifier(JpaDataSourceConfigCommon.PRIMARY_DATASOURCE_KEY) DataSource primaryDataSource,
                                                       @Qualifier(JpaDataSourceConfigCommon.SECONDAYR_DATASOURCE_KEY) DataSource secondaryDataSource) {
        DynamicDataSourceRouter proxy = new DynamicDataSourceRouter();
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(JpaDataSourceConfigCommon.PRIMARY_DATASOURCE_KEY, primaryDataSource);
        targetDataSources.put(JpaDataSourceConfigCommon.SECONDAYR_DATASOURCE_KEY, secondaryDataSource);

        proxy.setDefaultTargetDataSource(primaryDataSource);
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

    @Bean(name = "entityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder, @Qualifier("routingDataSource") DataSource routingDataSource) {
        return builder
                .dataSource(routingDataSource)//关键：注入routingDataSource
                .packages("com.sam.demo")
                //.persistenceUnit("default")
                .build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("routingDataSource") DataSource routingDataSource) {
        return this.entityManagerFactoryBean(builder, routingDataSource).getObject();
    }

//    @Primary
//    @Bean(name = "transactionManager")
//    public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder, @Qualifier("routingDataSource") DataSource routingDataSource) {
//        return new JpaTransactionManager(entityManagerFactory(builder, routingDataSource));
//    }

}
